const formidable = require("formidable");
const path = require("path");
const nanoid = require("nanoid");
const fs = require("fs");

// 模拟用户数据
const userData = [
    {
        userNumber: "admin",
        passWord: "111111",
        token: "tokenAdmin",
        userName: "admin管理员",
        avatar: "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
        routes: ["Product", "Acl", "aclUser", "aclRole", "aclMenus"],
        userId: "xxxxxx",
    },
    {
        userNumber: "test",
        passWord: "111111",
        token: "tokenTest",
        userName: "测试用户",
        avatar: "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
        routes: ["Product"],
        userId: "yyyyyy",
    },
];

/**
 * 用户登录处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.login_handler = async (req, res) => {
    const { userNumber, passWord } = req.body;
    console.log(userNumber, passWord + "@@用户登陆@@");
    const user = userData.find((u) => u.userNumber === userNumber);
    if (!user) return res.status(404).json({ code: 404, message: "账号不存在" });
    if (user.passWord !== passWord)
        return res.status(401).json({ code: 401, message: "密码错误" });

    res.json({ code: 200, token: user.token, message: "登录成功" });
};

/**
 * 获取用户信息处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getUserinfo_handler = async (req, res) => {
    const token = req.headers.token;
    const user = userData.find((u) => u.token === token);
    if (!user) return res.status(401).json({ code: 401, message: "用户已注销或TOKEN已过期" });

    res.json({
        code: 200,
        data: {
            userName: user.userName,
            avatar: user.avatar,
            routes: user.routes,
            userId: user.userId,
        },
    });
};

// 从原有的 getBrandData_handler 函数中提取品牌数据，作为全局变量
const brandData = [
    {
        id: "1",
        logoUrl: "127.0.0.1:3000/images/123.jpg",
        tmName: "品牌1",
        createTime: "2024-01-01 10:00:00",
        updateTime: "2024-01-02 14:30:00",
    },
    {
        id: "2",
        logoUrl: "127.0.0.1:3000/images/456.jpg",
        tmName: "品牌2",
        createTime: "2024-02-15 09:15:00",
        updateTime: "2024-02-20 16:45:00",
    },
    {
        id: "3",
        logoUrl: "127.0.0.1:3000/images/789.jpg",
        tmName: "品牌3",
        createTime: "2024-03-10 11:45:00",
        updateTime: "2024-03-12 13:20:00",
    },
    {
        id: "4",
        logoUrl: "127.0.0.1:3000/images/abc.jpg",
        tmName: "品牌4",
        createTime: "2024-04-22 15:30:00",
        updateTime: "2024-04-25 17:10:00",
    },
    {
        id: "5",
        logoUrl: "127.0.0.1:3000/images/def.jpg",
        tmName: "品牌5",
        createTime: "2024-05-05 12:00:00",
        updateTime: "2024-05-08 14:45:00",
    },
    {
        id: "6",
        logoUrl: "127.0.0.1:3000/images/ghi.jpg",
        tmName: "品牌6",
        createTime: "2024-06-12 13:30:00",
        updateTime: "2024-06-15 15:45:00",
    },
    {
        id: "7",
        logoUrl: "127.0.0.1:3000/images/jkl.jpg",
        tmName: "品牌7",
        createTime: "2024-07-20 14:15:00",
        updateTime: "2024-07-22 16:30:00",
    },
    {
        id: "8",
        logoUrl: "127.0.0.1:3000/images/mno.jpg",
        tmName: "品牌8",
        createTime: "2024-08-05 10:45:00",
        updateTime: "2024-08-08 12:00:00",
    },
    {
        id: "9",
        logoUrl: "127.0.0.1:3000/images/pqr.jpg",
        tmName: "品牌9",
        createTime: "2024-09-18 11:30:00",
        updateTime: "2024-09-20 13:45:00",
    },
    {
        id: "10",
        logoUrl: "127.0.0.1:3000/images/stu.jpg",
        tmName: "品牌10",
        createTime: "2024-10-25 12:45:00",
        updateTime: "2024-10-28 14:00:00",
    },
    {
        id: "11",
        logoUrl: "127.0.0.1:3000/images/vwx.jpg",
        tmName: "品牌11",
        createTime: "2024-11-02 13:30:00",
        updateTime: "2024-11-05 15:45:00",
    },
    {
        id: "12",
        logoUrl: "127.0.0.1:3000/images/yz1.jpg",
        tmName: "品牌12",
        createTime: "2024-12-10 14:15:00",
        updateTime: "2024-12-12 16:30:00",
    },
    {
        id: "13",
        logoUrl: "127.0.0.1:3000/images/234.jpg",
        tmName: "品牌13",
        createTime: "2025-01-15 10:45:00",
        updateTime: "2025-01-18 12:00:00",
    },
    {
        id: "14",
        logoUrl: "127.0.0.1:3000/images/567.jpg",
        tmName: "品牌14",
        createTime: "2025-02-22 11:30:00",
        updateTime: "2025-02-24 13:45:00",
    },
    {
        id: "15",
        logoUrl: "127.0.0.1:3000/images/890.jpg",
        tmName: "品牌15",
        createTime: "2025-03-05 12:45:00",
        updateTime: "2025-03-08 14:00:00",
    },
    {
        id: "16",
        logoUrl: "127.0.0.1:3000/images/abc1.jpg",
        tmName: "品牌16",
        createTime: "2025-04-12 13:30:00",
        updateTime: "2025-04-15 15:45:00",
    },
    {
        id: "17",
        logoUrl: "127.0.0.1:3000/images/def1.jpg",
        tmName: "品牌17",
        createTime: "2025-05-20 14:15:00",
        updateTime: "2025-05-22 16:30:00",
    },
    {
        id: "18",
        logoUrl: "127.0.0.1:3000/images/ghi1.jpg",
        tmName: "品牌18",
        createTime: "2025-06-05 10:45:00",
        updateTime: "2025-06-08 12:00:00",
    },
    {
        id: "19",
        logoUrl: "127.0.0.1:3000/images/jkl1.jpg",
        tmName: "品牌19",
        createTime: "2025-07-18 11:30:00",
        updateTime: "2025-07-20 13:45:00",
    },
    {
        id: "20",
        logoUrl: "127.0.0.1:3000/images/mno1.jpg",
        tmName: "品牌20",
        createTime: "2025-08-25 12:45:00",
        updateTime: "2025-08-28 14:00:00",
    }
];

/**
 * 获取品牌数据处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getBrandData_handler = async (req, res) => {
    // 从请求参数中获取 currentPage 和 pageSize
    const { currentPage = 1, pageSize = 10 } = req.params;
    console.log(req.headers + "@@获取品牌数据@@");
    // 模拟品牌数据
    // const brandData = [
    //     {
    //         id: "1",
    //         logoUrl: "127.0.0.1:3000/images/123.jpg",
    //         tmName: "品牌1",
    //         createTime: "2024-01-01 10:00:00",
    //         updateTime: "2024-01-02 14:30:00",
    //     },
    //     {
    //         id: "2",
    //         logoUrl: "127.0.0.1:3000/images/456.jpg",
    //         tmName: "品牌2",
    //         createTime: "2024-02-15 09:15:00",
    //         updateTime: "2024-02-20 16:45:00",
    //     },
    //     {
    //         id: "3",
    //         logoUrl: "127.0.0.1:3000/images/789.jpg",
    //         tmName: "品牌3",
    //         createTime: "2024-03-10 11:45:00",
    //         updateTime: "2024-03-12 13:20:00",
    //     },
    //     {
    //         id: "4",
    //         logoUrl: "127.0.0.1:3000/images/abc.jpg",
    //         tmName: "品牌4",
    //         createTime: "2024-04-22 15:30:00",
    //         updateTime: "2024-04-25 17:10:00",
    //     },
    //     {
    //         id: "5",
    //         logoUrl: "127.0.0.1:3000/images/def.jpg",
    //         tmName: "品牌5",
    //         createTime: "2024-05-05 12:00:00",
    //         updateTime: "2024-05-08 14:45:00",
    //     },
    //     {
    //         id: "6",
    //         logoUrl: "127.0.0.1:3000/images/ghi.jpg",
    //         tmName: "品牌6",
    //         createTime: "2024-06-12 13:30:00",
    //         updateTime: "2024-06-15 15:45:00",
    //     },
    //     {
    //         id: "7",
    //         logoUrl: "127.0.0.1:3000/images/jkl.jpg",
    //         tmName: "品牌7",
    //         createTime: "2024-07-20 14:15:00",
    //         updateTime: "2024-07-22 16:30:00",
    //     },
    //     {
    //         id: "8",
    //         logoUrl: "127.0.0.1:3000/images/mno.jpg",
    //         tmName: "品牌8",
    //         createTime: "2024-08-05 10:45:00",
    //         updateTime: "2024-08-08 12:00:00",
    //     },
    //     {
    //         id: "9",
    //         logoUrl: "127.0.0.1:3000/images/pqr.jpg",
    //         tmName: "品牌9",
    //         createTime: "2024-09-18 11:30:00",
    //         updateTime: "2024-09-20 13:45:00",
    //     },
    //     {
    //         id: "10",
    //         logoUrl: "127.0.0.1:3000/images/stu.jpg",
    //         tmName: "品牌10",
    //         createTime: "2024-10-25 12:45:00",
    //         updateTime: "2024-10-28 14:00:00",
    //     },
    //     {
    //         id: "11",
    //         logoUrl: "127.0.0.1:3000/images/vwx.jpg",
    //         tmName: "品牌11",
    //         createTime: "2024-11-02 13:30:00",
    //         updateTime: "2024-11-05 15:45:00",
    //     },
    //     {
    //         id: "12",
    //         logoUrl: "127.0.0.1:3000/images/yz1.jpg",
    //         tmName: "品牌12",
    //         createTime: "2024-12-10 14:15:00",
    //         updateTime: "2024-12-12 16:30:00",
    //     },
    //     {
    //         id: "13",
    //         logoUrl: "127.0.0.1:3000/images/234.jpg",
    //         tmName: "品牌13",
    //         createTime: "2025-01-15 10:45:00",
    //         updateTime: "2025-01-18 12:00:00",
    //     },
    //     {
    //         id: "14",
    //         logoUrl: "127.0.0.1:3000/images/567.jpg",
    //         tmName: "品牌14",
    //         createTime: "2025-02-22 11:30:00",
    //         updateTime: "2025-02-24 13:45:00",
    //     },
    //     {
    //         id: "15",
    //         logoUrl: "127.0.0.1:3000/images/890.jpg",
    //         tmName: "品牌15",
    //         createTime: "2025-03-05 12:45:00",
    //         updateTime: "2025-03-08 14:00:00",
    //     },
    //     {
    //         id: "16",
    //         logoUrl: "127.0.0.1:3000/images/abc1.jpg",
    //         tmName: "品牌16",
    //         createTime: "2025-04-12 13:30:00",
    //         updateTime: "2025-04-15 15:45:00",
    //     },
    //     {
    //         id: "17",
    //         logoUrl: "127.0.0.1:3000/images/def1.jpg",
    //         tmName: "品牌17",
    //         createTime: "2025-05-20 14:15:00",
    //         updateTime: "2025-05-22 16:30:00",
    //     },
    //     {
    //         id: "18",
    //         logoUrl: "127.0.0.1:3000/images/ghi1.jpg",
    //         tmName: "品牌18",
    //         createTime: "2025-06-05 10:45:00",
    //         updateTime: "2025-06-08 12:00:00",
    //     },
    //     {
    //         id: "19",
    //         logoUrl: "127.0.0.1:3000/images/jkl1.jpg",
    //         tmName: "品牌19",
    //         createTime: "2025-07-18 11:30:00",
    //         updateTime: "2025-07-20 13:45:00",
    //     },
    //     {
    //         id: "20",
    //         logoUrl: "127.0.0.1:3000/images/mno1.jpg",
    //         tmName: "品牌20",
    //         createTime: "2025-08-25 12:45:00",
    //         updateTime: "2025-08-28 14:00:00",
    //     }
    // ];
    
    const startIndex = (parseInt(currentPage) - 1) * parseInt(pageSize);
    const endIndex = startIndex + parseInt(pageSize);
    const tableData = brandData.slice(startIndex, endIndex);
    const total = brandData.length;

    res.json({
        code: 200,
        data: {
            tableData,
            total,
        },
    });
};

// 添加品牌数据
// post请求,会携带品牌名称tmName和图片logoURL过来
exports.addBrandData_handler = async (req, res) => {
    try {
        const { tmName, logoUrl } = req.body;

        // 生成新的品牌 ID
        const newId = (parseInt(brandData[brandData.length - 1].id) + 1).toString();


        // 构建新的品牌数据
        const newBrand = {
            id: newId,
            tmName,
            logoUrl, // 使用拼接后的地址
            createTime: new Date().toLocaleString(),
            updateTime: new Date().toLocaleString()
        };

        // 将新的品牌数据添加到全局变量中
        brandData.push(newBrand);

        res.json({ code: 200, message: "品牌数据添加成功", newBrand });
    } catch (error) {
        console.error('添加品牌数据时出错:', error);
        return res.status(500).json({ code: 500, message: `添加品牌数据失败: ${error.message}` });
    }
};

/**
 * 上传品牌图片处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.uploadImg_handler = async (req, res) => {
    const form = new formidable.IncomingForm();
    form.uploadDir = path.join(__dirname, "../public/images");
    form.keepExtensions = true;
    console.log("@@上传图片@@")

    form.parse(req, (err, fields, files) => {
        // console.log(fields) 
        // console.log(files)
        if (err) {
            console.error('文件解析错误:', err);
            return res.status(500).json({ code: 500, message: `文件解析失败: ${err.message}` });
        }

        const { brandId, brandName } = fields;
        const { file } = files;

        if (!file) {
            return res.status(400).json({ code: 400, message: "未找到上传的文件" });
        }

        try {
            // 从 files.file 数组中取出第一个元素
            const fileObj = files.file[0];

            // 检查 fileObj.filepath 是否有效
            if (!fileObj.filepath) {
                return res.status(500).json({ code: 500, message: "文件路径无效" });
            }

            // 可以在这里添加更多的文件处理逻辑，例如重命名文件
            const newFileName = `${nanoid()}-${fileObj.originalFilename}`;
            const newFilePath = path.join(form.uploadDir, newFileName);

            // 检查目标目录是否存在，如果不存在则创建
            const targetDir = path.dirname(newFilePath);
            if (!fs.existsSync(targetDir)) {
                fs.mkdirSync(targetDir, { recursive: true });
            }

            // 重命名文件
            fs.renameSync(fileObj.filepath, newFilePath);

            // 修改返回的 filePath 为客户端可访问的 URL
            const baseUrl = 'http://127.0.0.1:3000';
            const imageUrl = `${baseUrl}/images/${newFileName}`;

            res.json({ code: 200, message: "上传成功", filePath: imageUrl });
        } catch (error) {
            console.error('文件处理错误:', error);
            return res.status(500).json({ code: 500, message: `文件处理失败: ${error.message}` });
        }
    });
};

/**
 * 获取用户列表处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getAclUserData_handler = async (req, res) => {
    res.json({
        code: 200,
        data: {
            userData,
        },
    });
};

/**
 * 创建用户处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.createUserData_handler = async (req, res) => {
    const { userData } = req.body;
    const existingUser = userData.find((u) => u.userNumber === userData.userNumber);
    if (existingUser) return res.status(400).json({ code: 400, message: "用户账号不能相同" });

    // 模拟创建用户逻辑
    userData.push(userData);
    res.json({ code: 200, message: "创建成功" });
};

/**
 * 编辑用户处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.editUserData_handler = async (req, res) => {
    const { userData } = req.body;
    const index = userData.findIndex((u) => u.id === userData.id);
    if (index === -1) return res.status(404).json({ code: 404, message: "用户不存在" });

    // 模拟编辑用户逻辑
    userData[index] = { ...userData[index], ...userData };
    res.json({ code: 200, message: "编辑成功" });
};

/**
 * 删除用户处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.delUserData_handler = async (req, res) => {
    const { idArr } = req.body;
    const newUserData = userData.filter((u) => !idArr.includes(u.id));
    userData.length = 0;
    userData.push(...newUserData);
    res.json({ code: 200, message: "删除成功" });
};

/**
 * 更改用户状态处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.changeState_handler = async (req, res) => {
    const { token, state } = req.body;
    const user = userData.find((u) => u.token === token);
    if (!user) return res.status(404).json({ code: 404, message: "用户不存在" });

    user.state = state;
    res.json({ code: 200, message: "状态更新成功" });
};

/**
 * 获取异步路由配置处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getAsyncRoute_handler = async (req, res) => {
    const token = req.headers.token;
    const user = userData.find((u) => u.token === token);
    if (!user) return res.status(401).json({ code: 401, message: "用户已注销或TOKEN已过期" });

    // 模拟异步路由配置数据
    const asyncRoutes = [
        // 路由配置项
    ];
    res.json({
        code: 200,
        data: {
            asyncRoutes,
        },
    });
};

/**
 * 分配用户权限处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.distribute_handler = async (req, res) => {
    const { userToken, routes } = req.body;
    const user = userData.find((u) => u.token === userToken);
    if (!user) return res.status(404).json({ code: 404, message: "用户不存在" });

    user.routes = routes;
    res.json({ code: 200, message: "权限分配成功" });
};

/**
 * 获取系统消息处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getMessage_handler = async (req, res) => {
    const token = req.headers.token;
    const user = userData.find((u) => u.token === token);
    if (!user) return res.status(401).json({ code: 401, message: "用户已注销或TOKEN已过期" });

    // 模拟系统消息数据
    const messageData = [
        // 消息数据项
    ];
    res.json({
        code: 200,
        data: {
            messageData,
        },
    });
};

/**
 * 添加系统消息处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.addMessage_handler = async (req, res) => {
    // 模拟添加系统消息逻辑
    res.json({ code: 200, message: "留言成功" });
};

/**
 * 修改品牌数据处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.updateBrandData_handler = async (req, res) => {
    try {
        const { id, tmName, logoUrl } = req.body;

        // 查找要修改的品牌数据
        const brandIndex = brandData.findIndex(brand => brand.id === id);

        if (brandIndex === -1) {
            return res.status(404).json({ code: 404, message: "未找到该品牌数据" });
        }

        // 更新品牌数据
        const updatedBrand = {
            ...brandData[brandIndex],
            tmName,
            logoUrl,
            updateTime: new Date().toLocaleString()
        };

        // 更新全局变量中的品牌数据
        brandData[brandIndex] = updatedBrand;

        res.json({ code: 200, message: "品牌数据修改成功", updatedBrand });
    } catch (error) {
        console.error('修改品牌数据时出错:', error);
        return res.status(500).json({ code: 500, message: `修改品牌数据失败: ${error.message}` });
    }
};

/**
 * 删除品牌数据处理函数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.deleteBrandData_handler = async (req, res) => {
    try {
        const { id } = req.params;

        // 查找要删除的品牌数据的索引
        const brandIndex = brandData.findIndex(brand => brand.id === id);

        if (brandIndex === -1) {
            return res.status(404).json({ code: 404, message: "未找到该品牌数据" });
        }

        // 从品牌数据数组中删除该品牌
        const deletedBrand = brandData.splice(brandIndex, 1)[0];

        res.json({ code: 200, message: "品牌数据删除成功", deletedBrand });
    } catch (error) {
        console.error('删除品牌数据时出错:', error);
        return res.status(500).json({ code: 500, message: `删除品牌数据失败: ${error.message}` });
    }
};

